package com.example.hutudshelf.security.filter;

import com.example.hutudshelf.security.MyGrantedAuthority;
import com.example.hutudshelf.security.MyUserDetailsSercie;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.ArrayList;

@Component
@RequiredArgsConstructor
@Slf4j
public class TokenFilter extends GenericFilterBean {

    /**
     * 通过实现一个过滤器,对携带token的请求进行效验,然后把这个过滤器放在UsernamePasswordAuthenticationFilter之前
     * @author  xiaohu0305
     * @param servletRequest    请求
     * @param servletResponse   响应
     * @param filterChain       security的过滤器链
     * @time                    2025-4-18
     * @return                  void
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        String token = servletRequest1.getHeader("Authorization");
        // 先直接放行
        // String token = "token";
        if (StringUtils.hasText(token)) {
            log.info("检测到Token => {} !,封装对象,然后放行!!!!", token);
            // UsernamePasswordAuthenticationFilter 会根据当前是否持有Authentication对象来决定放行还是拦截,如果有,不会执行重复的逻辑
            ArrayList<MyGrantedAuthority> myGrantedAuthorities = new ArrayList<>();
            myGrantedAuthorities.add(new MyGrantedAuthority("ROLE_ADMIN"));
            UsernamePasswordAuthenticationToken htd = new UsernamePasswordAuthenticationToken(token,"", myGrantedAuthorities);
            // 在security的上下文中,将用户传递进去,传递进去后,后面的过滤器链都能使用
            SecurityContextHolder.getContext().setAuthentication(htd);
        }
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
